<template>
  <div class="chat-container">
    <chat-header title="教师专业发展助手" @onClose="close"></chat-header>
    <chat-content :messageList="displayedMessages" :isStreaming="isStreaming"></chat-content>
    <chat-footer @onSubmit="sendMessage" :loading="isStreaming" @onCancel="abortStreaming"></chat-footer>
  </div>
</template>

<script setup>
  import { onMounted } from 'vue';
  import ChatHeader from './components/ChatHeader.vue';
  import ChatContent from './components/ChatContent.vue';
  import ChatFooter from './components/ChatFooter.vue';
  import { useChatStore } from '@/stores/chat';
  import { useUserStore } from '@/stores/user';
  import { storeToRefs } from 'pinia';
  import { closeIframe } from '@/utils/pageCommunication';
  import { setToken } from '@/utils/tokenUtils';

  const { addMessage, clearMessages, fetchAIResponse, mockAIResponse, abortStreaming } = useChatStore();
  const { displayedMessages, isStreaming, streamingMessage } = storeToRefs(useChatStore());
  const { getUserInfo } = useUserStore();
  // 关闭窗口 由于iframe嵌入 因此变成关闭窗口
  const close = () => {
    // 关闭窗口 由于浏览器安全策略不可用
    // window.close();
    // 清空所有消息
    clearMessages();
    // 向父窗口发送关闭指令
    closeIframe();
  };

  onMounted(() => {
    // 将意外终止的思考信息清空 并放入对话列表中
    abortStreaming();
    // 获取用户信息
    getUserInfo();
    // 监听来自父窗口的消息
    window.addEventListener('message', event => {
      if (event.origin !== window.parent.location.origin) return;
      if (event.data.action === 'getToken') {
        setToken(event.data.token);
      }
    });
  });

  // 发送消息处理函数
  const sendMessage = async newMessage => {
    console.log(newMessage);
    const inputText = newMessage[0];
    const inputTeacher = newMessage[1];
    // 空消息检查
    if (!inputText?.trim()) return;
    isStreaming.value = true;
    // 添加用户消息到store
    addMessage(inputText, true);

    // 调用store方法获取AI响应
    await fetchAIResponse(inputText, inputTeacher);
    // 假数据 模拟AI响应
    // await mockAIResponse(newMessage);
  };
</script>

<style lang="scss" scoped>
  .chat-container {
    position: relative;
    padding-top: 36px;
    padding-bottom: 60px;
    display: flex;
    flex-direction: column;
    width: 600px;
    height: 696px;
    background: url(/bg.png) no-repeat center / 100% 100%;
  }
</style>
